/**
 * 我的课程页面组件
 * 功能：展示用户创建的课程和参加的课程
 * 主要功能：
 * 1. 课程管理：查看、编辑和删除创建的课程
 * 2. 课程学习：查看参加的课程和学习进度
 * 3. 课程表：查看课程时间安排
 * 4. 权限控制：根据用户角色显示不同功能
 */
<template>
  <div class="my-courses-container">
    <div class="page-header">
      <h1>我的课程</h1>
      <div class="header-tabs">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <el-tab-pane v-if="canManageCourses" label="我创建的课程" name="created">
            <div class="course-grid" v-if="createdCourses.length > 0">
              <div v-for="course in createdCourses" :key="course.courseId" class="course-card" @click="viewCourse(course.courseId)">
                <div class="course-image" :style="{ backgroundImage: `url(${course.titleImg || defaultImage})` }">
                  <div class="course-status" :class="course.status === 1 ? 'active' : 'inactive'">
                    {{ course.status === 1 ? '已发布' : '未发布' }}
                  </div>
                </div>
                <div class="course-info">
                  <h3 class="course-title">{{ course.title }}</h3>
                  <div class="course-meta">
                    <span class="course-category">{{ getCategoryName(course.categoryId) }}</span>
                    <span class="course-date">{{ formatDate(course.createTime) }}</span>
                  </div>
                  <div class="course-stats">
                    <div class="stat">
                      <i class="el-icon-user"></i>
                      <span>{{ course.studyPeople || 0 }}人学习</span>
                    </div>
                    <div class="stat">
                      <i class="el-icon-star-off"></i>
                      <span>{{ course.recommendWeight || 0 }}人收藏</span>
                    </div>
                  </div>
                  <div class="course-actions" @click.stop>
                    <el-button type="primary" size="small" @click="editCourse(course.courseId)">编辑</el-button>
                    <el-button type="danger" size="small" @click="deleteCourse(course.courseId)">删除</el-button>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="empty-state">
              <img src="https://edu-image.nosdn.127.net/18C76E2B6FD046A68C3B3AF8FA2013AC.png" alt="暂无课程" class="empty-image">
              <p>您还没有创建任何课程</p>
              <el-button type="primary" @click="createNewCourse">创建课程</el-button>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="我参加的课程" name="enrolled">
            <div class="course-grid" v-if="enrolledCourses.length > 0">
              <div v-for="course in enrolledCourses" :key="course.courseId" class="course-card" @click="goToCourseStudy(course)">
                <div class="course-image" :style="{ backgroundImage: `url(${course.titleImg || defaultImage})` }">
                  <div class="course-status" :class="{ 'completed': isCourseCompleted(course), 'pending': !isCourseCompleted(course) }">
                    {{ isCourseCompleted(course) ? '已完成' : '未完成' }}
                  </div>
                </div>
                <div class="course-info">
                  <h3 class="course-title">{{ course.title }}</h3>
                  <div class="course-schedule">
                    <div class="schedule-item">
                      <i class="el-icon-date"></i>
                      <span>上课日期：{{ course.teacherSchedule?.[0]?.date || '未设置' }}</span>
                    </div>
                    <div class="schedule-item">
                      <i class="el-icon-time"></i>
                      <span>上课时间：{{ course.teacherSchedule?.[0]?.startTime || '未设置' }} - {{ course.teacherSchedule?.[0]?.endTime || '未设置' }}</span>
                    </div>
                  </div>
                  <div class="course-progress-wrapper">
                    <el-progress 
                      :percentage="isCourseCompleted(course) ? 100 : 0"
                      :status="isCourseCompleted(course) ? 'success' : 'warning'"
                      :stroke-width="10"
                      :show-text="false"
                    ></el-progress>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="empty-state">
              <img src="https://edu-image.nosdn.127.net/9BC87EA8B0E046D1A77390E2861575A5.jpg" alt="暂无参加的课程" class="empty-image">
              <p>您还没有参加任何课程</p>
              <el-button type="primary" @click="browseCourses">浏览课程</el-button>
            </div>
          </el-tab-pane>

          <el-tab-pane label="课程表" name="schedule">
            <div class="schedule-container">
              <div class="schedule-header">
                <div class="schedule-title">课程周安排</div>
                <div class="schedule-controls">
                  <el-button type="primary" @click="previousWeek">上一周</el-button>
                  <span class="week-range">{{ weekRangeText }}</span>
                  <el-button type="primary" @click="nextWeek">下一周</el-button>
                </div>
                <div class="schedule-legend">
                  <div class="legend-item">
                    <div class="legend-color course-booked"></div>
                    <span>已预约</span>
                  </div>
                  <div class="legend-item">
                    <div class="legend-color course-completed"></div>
                    <span>已完成</span>
                  </div>
                  <div class="legend-item">
                    <div class="legend-color course-rated"></div>
                    <span>已评价</span>
                  </div>
                </div>
              </div>
              
              <div class="schedule-grid">
                <div class="time-column">
                  <div class="grid-header"></div>
                  <div v-for="time in timeSlots" :key="time" class="time-slot">
                    {{ time }}
                  </div>
                </div>
                
                <div v-for="(date, index) in getWeekDates(currentWeek)" 
                     :key="date" 
                     class="day-column">
                  <div class="grid-header">
                    <div class="weekday">{{ getWeekDay(index) }}</div>
                    <div class="date">{{ formatWeekDate(date) }}</div>
                  </div>
                  
                  <div v-for="time in timeSlots" 
                       :key="time" 
                       class="schedule-cell"
                       :class="{ 
                         [getCourseStatusClass(getCourseInTimeSlot(date, time)?.status)]: getCourseInTimeSlot(date, time)
                       }">
                    <template v-if="getCourseInTimeSlot(date, time)">
                      <div class="course-info-mini">
                        <div class="course-name">{{ getCourseName(getCourseInTimeSlot(date, time)) }}</div>
                        <div class="course-time">{{ getCourseInTimeSlot(date, time).startTime.substring(0, 5) }} - {{ getCourseInTimeSlot(date, time).endTime.substring(0, 5) }}</div>
                        <div class="course-status">{{ getCourseStatusText(getCourseInTimeSlot(date, time).status) }}</div>
                      </div>
                    </template>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElTabs, ElTabPane, ElButton, ElProgress } from 'element-plus'
import { getCreatedCourses, deleteCourse as deleteCourseAPI, selectCourseByUserId } from '@/api/course'
import { isTeacherOrAdmin } from '@/utils/permission'
import request from '@/utils/request'

export default {
  name: 'MyCourses',
  components: {
    ElTabs,
    ElTabPane,
    ElButton,
    ElProgress
  },
  
  setup() {
    // 路由和状态管理
    const router = useRouter()
    const activeTab = ref('enrolled')
    const createdCourses = ref([])
    const enrolledCourses = ref([])
    const courseTable = ref([])
    const currentWeek = ref(new Date())
    const timeSlots = ref(['08:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00'])
    const defaultImage = 'https://edu-image.nosdn.127.net/C7F81100F90F8DB85704C901C4CFFC9D.jpg'
    
    /**
     * 获取一周的日期范围
     * @param {Date} date - 基准日期
     * @returns {Array<Date>} 一周的日期数组
     */
    const getWeekDates = (date) => {
      const curr = new Date(date)
      const week = []
      curr.setDate(curr.getDate() - curr.getDay() + 1)
      for (let i = 0; i < 7; i++) {
        week.push(new Date(curr))
        curr.setDate(curr.getDate() + 1)
      }
      return week
    }

    /**
     * 获取星期几的中文表示
     * @param {number} index - 星期索引（0-6）
     * @returns {string} 星期几的中文表示
     */
    const getWeekDay = (index) => {
      const weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      return weekDays[index]
    }

    /**
     * 格式化日期显示
     * @param {Date} date - 日期对象
     * @returns {string} 格式化后的日期字符串
     */
    const formatWeekDate = (date) => {
      return `${String(date.getMonth() + 1).padStart(2, '0')}月${String(date.getDate()).padStart(2, '0')}日`
    }

    /**
     * 获取当前周的日期范围显示文本
     */
    const weekRangeText = computed(() => {
      const weekDates = getWeekDates(currentWeek.value)
      const start = weekDates[0]
      const end = weekDates[6]
      return `${start.getFullYear()}年${String(start.getMonth() + 1).padStart(2, '0')}月${String(start.getDate()).padStart(2, '0')}日 - ${String(end.getMonth() + 1).padStart(2, '0')}月${String(end.getDate()).padStart(2, '0')}日`
    })

    /**
     * 切换到上一周
     */
    const previousWeek = () => {
      const newDate = new Date(currentWeek.value)
      newDate.setDate(newDate.getDate() - 7)
      currentWeek.value = newDate
    }

    /**
     * 切换到下一周
     */
    const nextWeek = () => {
      const newDate = new Date(currentWeek.value)
      newDate.setDate(newDate.getDate() + 7)
      currentWeek.value = newDate
    }

    /**
     * 获取指定时间段的课程
     * @param {string} date - 日期
     * @param {string} time - 时间
     * @returns {Object|null} 课程信息或null
     */
        // 判断时间段是否有课程
        const getCourseInTimeSlot = (date, timeSlot) => {
      if (!courseTable.value) {
        return null;
      }
      const matchingCourse = courseTable.value.find(course => {
        const courseDate = new Date(course.date);
        const courseStartTime = course.startTime;
        const [courseStartHour] = courseStartTime.split(':').map(Number);
        const [slotHour] = timeSlot.split(':').map(Number);
        
        // 检查日期是否匹配（忽略时间部分）
        const dateMatch = courseDate.getFullYear() === date.getFullYear() &&
                         courseDate.getMonth() === date.getMonth() &&
                         courseDate.getDate() === date.getDate();
                         
        // 检查时间是否在同一个时间段（考虑2小时间隔）
        const timeMatch = courseStartHour >= slotHour && courseStartHour < (slotHour + 2);
        return dateMatch && timeMatch;
      });
      return matchingCourse;
    }

    /**
     * 获取课程表数据
     */
    const getCourseTable = async () => {
      try {
        const response = await request.get('/courseService/courseController/selectStudentCourseTable')
        
        if (response.code === 200) {
          if (!response.data || !Array.isArray(response.data)) {
            ElMessage.error('课程表数据格式不正确')
            return
          }
          
          // 确保日期和时间格式正确
          const formattedData = response.data.map(course => ({
            ...course,
            date: course.date,
            startTime: course.startTime,
            endTime: course.endTime
          }))
          
          courseTable.value = formattedData
          
          // 如果没有数据，显示提示
          if (formattedData.length === 0) {
            ElMessage.info('暂无课程安排')
          }
        } else {
          ElMessage.error(response.message || '获取课程表失败')
        }
      } catch (error) {
        ElMessage.error('获取课程表失败，请稍后重试')
      }
    }

    /**
     * 获取课程名称
     * @param {Object} course - 课程对象
     * @returns {string} 课程名称
     */
    const getCourseName = (course) => {
      return course.courseName
    }

    /**
     * 获取课程状态对应的CSS类名
     * @param {number} status - 课程状态
     * @returns {string} CSS类名
     */
    const getCourseStatusClass = (status) => {
      const statusMap = {
        1: 'course-booked',    // 已预约
        3: 'course-completed', // 已完成
        4: 'course-rated'      // 已评价
      }
      return statusMap[status] || ''
    }

    /**
     * 获取课程状态文本
     * @param {number} status - 课程状态
     * @returns {string} 状态文本
     */
    const getCourseStatusText = (status) => {
      const statusMap = {
        1: '已预约',
        3: '已完成',
        4: '已评价'
      }
      return statusMap[status] || ''
    }

    /**
     * 处理标签页切换
     * @param {Object} tab - 标签页对象
     */
    const handleTabClick = (tab) => {
      if (tab.props.name === 'created') {
        fetchCreatedCourses()
      } else if (tab.props.name === 'schedule') {
        getCourseTable()
      } else {
        fetchEnrolledCourses()
      }
    }

    /**
     * 检查用户是否有管理课程的权限
     */
    const canManageCourses = computed(() => {
      return isTeacherOrAdmin()
    })

    // 监听activeTab的变化
    watch(activeTab, (newTab) => {
      if (newTab === 'created' && !canManageCourses.value) {
        ElMessage.warning('您没有权限查看创建的课程')
        activeTab.value = 'enrolled'
      }
    })

    /**
     * 课程分类映射
     */
    const categories = {
      1: '学术',
      2: '技术与工程',
      3: '商业与管理',
      4: '艺术与设计',
      5: '职业技能',
      6: '健康与医学',
      7: '语言与文化',
      8: '科技与未来趋势',
      9: '体育与健身'
    }
    
    /**
     * 获取分类名称
     * @param {number} categoryId - 分类ID
     * @returns {string} 分类名称
     */
    const getCategoryName = (categoryId) => {
      return categories[categoryId] || '未分类'
    }
    
    /**
     * 格式化日期
     * @param {string} dateString - 日期字符串
     * @returns {string} 格式化后的日期
     */
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }
    
    /**
     * 格式化进度显示
     * @param {number} percentage - 进度百分比
     * @returns {string} 格式化后的进度文本
     */
    const progressFormat = (percentage) => {
      return percentage ? `${percentage}%` : '0%'
    }
    
    /**
     * 获取创建的课程列表
     */
    const fetchCreatedCourses = async () => {
      try {
        const response = await getCreatedCourses()
        if (response.code === 200) {
          createdCourses.value = response.data.filter(course => course.status === 0 || course.status === 1)
        } else {
          ElMessage.error(response.message || '获取课程信息失败')
        }
      } catch (error) {
        ElMessage.error('获取课程信息失败')
      }
    }
    
    /**
     * 获取参加的课程列表
     */
    const fetchEnrolledCourses = async () => {
      try {
        const response = await selectCourseByUserId()
        if (response.code === 200) {
          enrolledCourses.value = response.data.map(course => ({
            ...course,
            progress: 0  // 可以根据需要设置进度
          }))
        } else {
          ElMessage.error(response.message || '获取参加的课程失败')
        }
      } catch (error) {
        ElMessage.error('获取课程信息失败')
      }
    }
    
    /**
     * 查看课程详情
     * @param {string|number} courseId - 课程ID
     */
    const viewCourse = (courseId) => {
      router.push(`/course/${courseId}`)
    }
    
    /**
     * 编辑课程
     * @param {string|number} courseId - 课程ID
     */
    const editCourse = (courseId) => {
      router.push(`/course/edit/${courseId}`)
    }
    
    /**
     * 创建新课程
     */
    const createNewCourse = () => {
      router.push('/course/create')
    }
    
    /**
     * 浏览课程
     */
    const browseCourses = () => {
      router.push('/courses')
    }
    
    /**
     * 删除课程
     * @param {string|number} courseId - 课程ID
     */
    const deleteCourse = (courseId) => {
      ElMessageBox.confirm('确定要删除这门课程吗？此操作不可逆。', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await deleteCourseAPI(courseId)
          if (response && response.code === 200) {
            ElMessage.success('课程删除成功')
            // 从列表中移除被删除的课程
            createdCourses.value = createdCourses.value.filter(course => course.courseId !== courseId)
          } else {
            ElMessage.error(response?.message || '删除课程失败')
          }
        } catch (error) {
          ElMessage.error('删除课程失败，请稍后重试')
        }
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    }
    
    /**
     * 判断课程是否已完成
     * @param {Object} course - 课程对象
     * @returns {boolean} 是否已完成
     */
    const isCourseCompleted = (course) => {
      if (!course.teacherSchedule?.[0]) return false
      
      const schedule = course.teacherSchedule[0]
      const now = new Date()
      const courseDate = new Date(`${schedule.date} ${schedule.endTime}`)
      
      return now > courseDate
    }
    
    /**
     * 跳转到课程学习页面
     * @param {Object} course - 课程对象
     */
    const goToCourseStudy = (course) => {
      if (course.teacherSchedule && course.teacherSchedule.length > 0) {
        const scheduleId = course.teacherSchedule[0].scheduleId
        router.push({
          name: 'CourseStudy',
          params: { scheduleId: scheduleId }
        })
      } else {
        ElMessage.warning('该课程暂无课程安排')
      }
    }
    
    onMounted(() => {
      // 根据权限设置初始标签
      if (!canManageCourses.value) {
        activeTab.value = 'enrolled'
      }
      // 加载相应的课程数据
      handleTabClick({ props: { name: activeTab.value } })
    })
    
    return {
      activeTab,
      createdCourses,
      enrolledCourses,
      courseTable,
      currentWeek,
      timeSlots,
      defaultImage,
      weekRangeText,
      getWeekDates,
      getWeekDay,
      formatWeekDate,
      previousWeek,
      nextWeek,
      getCourseInTimeSlot,
      handleTabClick,
      canManageCourses,
      getCategoryName,
      formatDate,
      progressFormat,
      viewCourse,
      editCourse,
      createNewCourse,
      browseCourses,
      deleteCourse,
      isCourseCompleted,
      goToCourseStudy,
      getCourseTable,
      getCourseName,
      getCourseStatusClass,
      getCourseStatusText
    }
  }
}
</script>

<style scoped>
.my-courses-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
}

.course-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.course-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.course-card:hover {
  transform: translateY(-5px);
}

.course-image {
  height: 160px;
  background-size: cover;
  background-position: center;
  position: relative;
  overflow: hidden;
}

.course-image::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to bottom, rgba(0,0,0,0.2) 0%, rgba(0,0,0,0) 100%);
}

.course-status {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 13px;
  font-weight: bold;
  color: white;
  z-index: 2;
}

.course-status.completed {
  background-color: #67C23A;
}

.course-status.pending {
  background-color: #E6A23C;
}

.course-progress-wrapper {
  margin: 15px 0;
  padding: 0 5px;
}

.course-info {
  padding: 15px;
}

.course-title {
  margin: 0 0 10px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.course-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
  margin-bottom: 10px;
}

.course-stats {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
}

.stat {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
  color: #666;
}

.course-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.empty-image {
  width: 200px;
  margin-bottom: 20px;
}

.empty-state p {
  color: #666;
  margin-bottom: 20px;
}

:deep(.el-progress-bar__outer) {
  background-color: #f0f0f0 !important;
  border-radius: 10px;
  height: 10px !important;
}

:deep(.el-progress-bar__inner) {
  border-radius: 10px;
  transition: all 0.3s ease;
}

:deep(.el-progress--warning .el-progress-bar__inner) {
  background: linear-gradient(90deg, #E6A23C 0%, #F3D19E 100%);
}

:deep(.el-progress--success .el-progress-bar__inner) {
  background: linear-gradient(90deg, #67C23A 0%, #95F2A8 100%);
}

.course-schedule {
  margin: 10px 0;
}

.schedule-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.schedule-item i {
  color: #409EFF;
}

@media (max-width: 768px) {
  .course-grid {
    grid-template-columns: 1fr;
  }
  
  .my-courses-container {
    padding: 10px;
  }
}

.course-table-container {
  margin-top: 20px;
}

.status-pending {
  color: #409EFF;
}

.status-cancelled {
  color: #F56C6C;
}

.status-completed {
  color: #67C23A;
}

.status-rated {
  color: #909399;
}

.schedule-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.schedule-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 20px;
}

.schedule-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.schedule-controls {
  display: flex;
  align-items: center;
  gap: 16px;
}

.week-range {
  font-size: 16px;
  color: #666;
  min-width: 240px;
  text-align: center;
}

.schedule-legend {
  display: flex;
  gap: 16px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 4px;
}

.legend-color.course-booked {
  background-color: #67C23A;
}

.legend-color.course-completed {
  background-color: #409EFF;
}

.legend-color.course-rated {
  background-color: #909399;
}

.schedule-grid {
  display: flex;
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
}

.time-column {
  width: 80px;
  flex-shrink: 0;
  background: #fafafa;
}

.day-column {
  flex: 1;
  min-width: 120px;
  border-left: 1px solid #eee;
}

.grid-header {
  height: 60px;
  padding: 8px;
  background: #f0f7ff;
  border-bottom: 1px solid #eee;
  text-align: center;
}

.weekday {
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.date {
  font-size: 12px;
  color: #666;
}

.time-slot {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid #eee;
  color: #666;
  font-size: 14px;
}

.schedule-cell {
  height: 60px;
  border-bottom: 1px solid #eee;
  padding: 4px;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;  /* 设置默认背景色为白色 */
  border-radius: 6px;  /* 添加圆角 */
  margin: 2px;  /* 添加间距使圆角更明显 */
}

.schedule-cell.course-booked {
  background-color: #67C23A;
  color: white;
  border-radius: 6px;  /* 保持圆角一致 */
}

.schedule-cell.course-completed {
  background-color: #409EFF;
  color: white;
  border-radius: 6px;  /* 保持圆角一致 */
}

.schedule-cell.course-rated {
  background-color: #909399;
  color: white;
  border-radius: 6px;  /* 保持圆角一致 */
}

.schedule-cell:hover {
  background-color: #b7eb8f;
  border-radius: 6px;  /* 保持圆角一致 */
}

.course-info-mini {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 2px;
}

.course-name {
  font-weight: bold;
  font-size: 13px;
}

.course-time {
  font-size: 11px;
  opacity: 0.9;
}

.course-status {
  font-size: 11px;
  opacity: 0.8;
}
</style> 